package com.lagou.service.impl;

import com.lagou.dao.AuthCodeMapper;
import com.lagou.pojo.AuthCode;
import com.lagou.service.AuthCodeService;
import com.lagou.service.EmailService;
import org.apache.commons.lang.time.DateUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Random;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Reference
    private EmailService emailService;

    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Override
    public int test() {
        return 200;
    }

    @Override
    public AuthCode create(String email) {
        Date now = new Date();
        Random random = new Random();
        int code = random.nextInt(1000000);

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(String.valueOf(code));
        authCode.setCreatetime(now);
        authCode.setExpiretime(DateUtils.addMinutes(now, 10));
        AuthCode result = authCodeMapper.save(authCode);
        // 发送邮件
        emailService.sendEmail(email, String.valueOf(code));
        return result;
    }

    public AuthCode findLastAuthCode(String email){
        return authCodeMapper.findTop1ByEmailOrderByIdDesc(email);
    }


    public Integer validate(String email, String code){
        AuthCode lastAuthCode = findLastAuthCode(email);
        if(new Date().after(lastAuthCode.getExpiretime())){
            return 2;
        }
        if(code.equals(lastAuthCode.getCode())){
            return 0;
        }
        return 1;
    }
}
